<template>
  <div class="date-field">
    <input ref="inputRef" class="input" :name="name" :id="id" />
  </div>
</template>

<script setup lang="ts">
import { onMounted, onBeforeUnmount, ref, watch } from 'vue'
import flatpickr from 'flatpickr'
import 'flatpickr/dist/flatpickr.css'
import { Mandarin as zh } from 'flatpickr/dist/l10n/zh.js'

const props = defineProps<{ 
  modelValue?: string,
  mode?: 'date' | 'datetime',
  name?: string,
  id?: string
}>()

const emit = defineEmits<{
  (e: 'update:modelValue', v?: string): void
}>()

const inputRef = ref<HTMLInputElement>()
let fp: flatpickr.Instance | undefined

onMounted(() => {
  if (!inputRef.value) return
  const isDateTime = props.mode === 'datetime'
  fp = flatpickr(inputRef.value, {
    locale: zh,
    altInput: true,
    altFormat: isDateTime ? 'Y年m月d日 H:i:S' : 'Y年m月d日',
    dateFormat: isDateTime ? 'Y-m-d H:i:S' : 'Y-m-d',
    enableTime: isDateTime,
    enableSeconds: isDateTime,
    time_24hr: true,
    defaultDate: props.modelValue,
    onChange: (selectedDates, dateStr) => {
      emit('update:modelValue', dateStr || undefined)
    }
  })
})

watch(() => props.modelValue, (v) => {
  if (fp) fp.setDate(v || '')
})

onBeforeUnmount(() => {
  if (fp) fp.destroy()
})
</script>

<style scoped>
.date-field { width: 100%; }
.date-field :deep(.flatpickr-input) { width: 100%; }
</style>

